<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Traits\MovieWatcher;
use App\Models\Traits\InsertMovie;
use Illuminate\Support\Arr;
class Movie extends Model
{
    use MovieWatcher, InsertMovie;

    protected $fillable = [
                            'name',
                            'short_name',
                            'introduction',
                            'area',
                            'score',
                            'cover',
                            'outher_name',
                            'published_at',
                            'year',
                            'score_people',
                            'runtime',
                            'language',
                            'imdb',
                            'douban_id',
                            'is_crawler_player_source',
                            'is_crawler_comments'
                        ];

    public function scopeRecent($query)
    {
        // 按照创建时间排序
        return $query->orderBy('created_at', 'desc');
    }

    public function scopeNewUpdated($query)
    {
        // 按照剧集最新更新时间排序
        return $query->orderBy('score', 'desc')->orderBy('updated_at', 'desc');
    }

    public function bingeWatchers()
    {
        // 正在追的用户
        return $this->belongsToMany('App\Models\User', 'movie_watch_user')
                    ->withPivot('status')
                    ->withTimestamps()->using('App\Models\MovieWatchUser');
    }

    public function categories()
    {
        return $this->belongsToMany(Category::class)->withTimestamps();
    }

    public function directors()
    {
        //导演， 有可能有多个，所以是复数形式
        return $this->belongsToMany(Star::class, 'director_movie', 'movie_id', 'director_id');
    }

    public function actors()
    {
        // 主演
        return $this->belongsToMany(Star::class, 'actor_movie', 'movie_id', 'actor_id');
    }

    public function authors()
    {
        // 编剧
        return $this->belongsToMany(Star::class, 'author_movie', 'movie_id', 'author_id');
    }

    public function toESArray()
    {
        // 只取出需要的字段
        $arr = Arr::only($this->toArray(), [
            'id',
            'name',
            'outher_name',
            'year',
            'score',
            'score_people',
            'runtime',
            'short_name'
        ]);

        $arr['scores'] = $arr['score'] * $arr['score_people'];
        // 如果有类目，则 category 字段为类目名数组，否则为空字符串
        $arr['categories'] = $this->categories->map(function (Category $category) {
            return Arr::only($category->toArray(), ['name', 'id']);
        });
        // 如果有演员，则 actor 字段为类目名数组，否则为空字符串
        $arr['actors'] = $this->actors->map(function (Star $actor) {
            return Arr::only($actor->toArray(), ['name', 'id']);
        });
        $arr['authors'] = $this->authors->map(function (Star $author) {
            return Arr::only($author->toArray(), ['name', 'id']);
        });
        $arr['directors'] = $this->directors->map(function (Star $director) {
            return Arr::only($director->toArray(), ['name', 'id']);
        });
        // strip_tags 函数可以将 html 标签去除
        $arr['introduction'] = strip_tags($this->introduction);
        // 地区属性修改
        $arr['areas'] = $this->areas->map(function (Area $area) {
            return Arr::only($area->toArray(), ['name', 'id']);
        });
        return $arr;
    }

    public function collects()
    {   // 收录该电影的看单
        return $this->belongsToMany(Collect::class);
    }

    // 电影和 地区关联
    public function areas()
    {
        return $this->belongsToMany(Area::class, 'area_movie', 'movie_id', 'area_id');
    }

    // 电影和播放源关联
    public function player_sources()
    {
        return $this->hasMany(PlayerSource::class, 'movie_id');
    }
    /**
     * 添加电影播放源
     *
     * @param array $data 采集器处理过的播放源数据
     * @return void
     */
    public function addPlayerSources($data = [])
    {
        foreach ($data as $player) {
            $type = PlayerType::firstOrCreate(
                ['type' => $player['type']],
                ['name' => $player['name']]
            );

            $playerData = [
                'type_id' => $type->id,
                'is_free' => $player['is_free'],
                'is_vip_free' => $player['is_vip_free'],
                'content' => $player['content'],
                'url' => $player['url'],
                'movie_id' => $this->id,
            ];
            PlayerSource::create($playerData);
        }
        $this->update(['is_crawler_player_source' => true]);
    }

    /**
     * 电影的评论
     *
     * @return Comment
     */
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
    /**
     *
     */
    public function cover_image()
    {
        return $this->hasOne(Image::class);
    }
}
